#include "stdafx.h"
#include "Perft.h"


CPerft::CPerft()
{
}


CPerft::~CPerft()
{
}

BITBOARD CPerft::Start( CBoard * board, uint depth )
{
    SetState( BUSY );
    first_depth = depth;
    ply = Run( board, depth );
    SetState( FREE );
    return ply;
}

BITBOARD CPerft::Run( CBoard * board, uint depth )
{
    BITBOARD paths = 0;
    uint color = board->GetColor();
    if (IsStopped()) return paths;
    if ( !depth ) return 1;
    CMoveList list[1];
    chessmove.GenAll( board, list );
    list->Start();
    while ( !(list->IsEmpty()) )
    {
        uint move = list->GetMove();
        if ( chessmove.Do( board, move ) ) // the move could be done and is done
        {
            if ( !( board->UnderCheck( color ) ) ) // the king is not in check
            {
                BITBOARD local_paths = Run( board, depth-1);
                paths += local_paths;
                if ( first_depth == depth )
                {
                    list->PrintMove( move );
                    cout << " count = " << local_paths<<endl;
                }
            }
            chessmove.Undo( board, move );
        } 
        list->Next();
    }    
    return paths;
}